package com.shuo.dsa.niuke;

import com.shuo.dsa.model.ListNode;

/**
 * 输入一个链表，输出该链表中倒数第k个结点
 *      思路: 快慢指针, 记得留意k大于链表长度的情况
 */
public class FindKthToTail {
    public ListNode FindKthToTail(ListNode head, int k) {
        if (head == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while (k > 0) {
            if (fast == null)
                return null;
            fast = fast.next;
            k--;
        }
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
